#!/bin/bash

set -e

if [[ "${MIGRATION_ENABLED}" == "true" ]]; then
    echo "Running Django migrations"
    python manage.py makemigrations
    python manage.py migrate
fi

if [[ "${MODE}" == "worker" ]]; then

    # Get the number of available CPU cores
    if [ "${CELERY_AUTO_SCALE,,}" = "true" ]; then
        # Set MAX_WORKERS to the number of available cores if not specified
        AVAILABLE_CORES=$(nproc)
        MAX_WORKERS=${CELERY_MAX_WORKERS:-$AVAILABLE_CORES}
        MIN_WORKERS=${CELERY_MIN_WORKERS:-1}
        CONCURRENCY_OPTION="--autoscale=${MAX_WORKERS},${MIN_WORKERS}"
    else
        CONCURRENCY_OPTION="-c ${CELERY_WORKER_AMOUNT:-1}"
    fi

    exec celery -A ai_red_envelope.celery_app worker -P ${CELERY_WORKER_CLASS:-gevent} $CONCURRENCY_OPTION --loglevel ${LOG_LEVEL} \
        -Q ${CELERY_QUEUES:-default}

elif [[ "${MODE}" == "beat" ]]; then
    exec celery -A ai_red_envelope.celery_app beat --loglevel ${LOG_LEVEL}
else
    if [[ "${DEBUG}" == "true" ]]; then
        exec python manage.py runserver ${DJANGO_BIND_ADDRESS:-0.0.0.0}:${DJANGO_PORT:-8000} --settings=ai_red_envelope.settings
    else
        exec gunicorn \
            --bind "${DJANGO_BIND_ADDRESS:-0.0.0.0}:${DJANGO_PORT:-8000}" \
            --workers ${SERVER_WORKER_AMOUNT:-4} \
            --worker-class ${SERVER_WORKER_CLASS:-gevent} \
            --timeout ${GUNICORN_TIMEOUT:-120} \
            --preload \
            ai_red_envelope.wsgi:application
    fi
fi